package service

import (
	"errors"
	"github.com/vueadmin/app/admin/dto"
	"github.com/vueadmin/app/admin/model"
	"github.com/vueadmin/app/admin/vo"
	"github.com/vueadmin/global"
	"github.com/vueadmin/utils/conv"
	"gorm.io/gorm"
)

var AdminLoginService = new(adminLoginService)

type adminLoginService struct{}

// 后台登录
func (p adminLoginService) Login(req *dto.AdminLoginReq) (*vo.AdminLogin, error) {
	var entity vo.AdminLogin
	if err := global.DB.Model(&model.AdminAdminuser{}).Preload("Role").Where("user = ?", req.User).Limit(1).First(&entity).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("账号不存在！")
		} else {
			return nil, err
		}
	}
	if !conv.EqualsPassword(req.Pwd, entity.Pwd) {
		return nil, errors.New("密码输入错误！")
	}
	if entity.Role.Status == 0 || entity.Status == 0 {
		return nil, errors.New("账户被禁止登录！")
	}
	return &entity, nil
}
